import axios from 'axios'
import store from '@/store'
// import { getToken } from '@/utils/auth'
import { Toast } from 'cube-ui'
import Vue from 'vue'
import router from '@/router'
import code from '@/config/code'

Vue.use(Toast)

const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000 // request timeout
})

request.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters['ExecUser/token']) {
      // console.log(store.getters['ExecUser/token'])
      const tokenName = process.env.VUE_APP_TOKEN
      // config.headers['X-Token-YANG'] = store.getters['ExecUser/token']
      config.headers[tokenName] = store.getters['ExecUser/token']
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

request.interceptors.response.use(
  response => {
    const res = response.data

    // 根据后端定义的代码CODE_ERROR处理
    if (res.code !== code.CODE_SUCCESS) {
      // for debug
      console.log(res)

      let errMsg = res.message || '请求失败'
      let time = 1000

      // response.msg => object 模型错误
      // 只取1条错误
      if (typeof errMsg === 'object') {
        const arr = Object.keys(errMsg)
        errMsg = errMsg[arr[0]].join(',')
        time = 3000
        console.log(errMsg)
      }

      if (res.code !== code.CODE_ERROR_CUSTOM) {
        Toast.$create({
          time: time,
          type: 'error',
          txt: errMsg,
          mask: true
        }).show()
      }

      // nothing
      if (res.code === code.CODE_NOTHING) {
        Toast.$create({
          time: 1000,
          type: 'error',
          txt: '错误页面',
          mask: true,
          onTimeout: () => {
            router.replace({ path: '/error' })
          }
        }).show()
      }

      // token expired
      if (res.code === code.CODE_TOKEN_EXPIRED) {
        Toast.$create({
          time: 1000,
          type: 'error',
          txt: '登录过期,请重新登录!',
          mask: true,
          onTimeout: () => {
            router.replace({ path: '/user/login' })
          }
        }).show()
      }

      return Promise.reject(new Error(errMsg))
    } else {
      return res
    }
  },

  // 这里是非200的请求
  error => {
    console.log('请求错误' + error) // for debug

    const { msg } = error.response.data

    Toast.$create({
      time: 1000,
      type: 'error',
      txt: msg || '请求失败',
      mask: true
    }).show()

    return Promise.reject(error)
  }
)

export default request
